import BookServer from "../server/BookServer";
import { Request, Response } from 'express';

class BookController {

  // 添加图书
  async addBook(req: Request, res: Response) {
    const form = req.body;
    if (Object.keys(form).length < 9) return res.error('缺少必填参数！');
    form.price = Number(form.price)
    const book = await BookServer.findBookById(form.id);
    if (book) return res.error('图书编号已存在！');
    await BookServer.addBook(form);
    res.successMsg('添加图书成功！');
  }

  // 根据 id 删除图书
  async deleteBook(req: Request, res: Response) {
    await BookServer.delBook(req.params.id);
    res.successMsg('删除图书成功！');
  }

  // 修改图书
  async editBook(req: Request, res: Response) {
    const form = req.body;
    if (!form.id) return res.error('缺少必填参数！');
    // 处理价格
    form.price = Number(form.price)
    // 处理时间
    form.publish_time = new Date(form.publish_time).toLocaleDateString()
    await BookServer.updateBook(form.id, form);
    res.successMsg('更新图书成功！');
  }

  // 获取所有图书
  async getAllBooks(req:Request, res:Response) {
    const books = await BookServer.findAllBooks();
    res.success(books);
  }

  // 根据图书 id 获取图书
  async getBookById(req: Request, res: Response) {
    const books = await BookServer.findBookById(req.params.id);
    if (!books) return res.error('查无此图书！');
    res.success(books);
  }

  // 根据图书名称关键词获取图书
  async getBooksByNameKey(req: Request, res: Response) {
    const books = await BookServer.findBookByNameKey(req.body.bookNameKey);
    if (!books) return res.error('查询失败！');
    res.success(books);
  }

  // 根据图书类别名称关键词获取图书
  async getBooksByTypeKey(req: Request, res: Response) {
    const books = await BookServer.findBookByTypeKey(req.body.bookTypeKey);
    if (!books) return res.error('查询失败！');
    res.success(books);
  }

  // 根据图书作者关键词获取图书
  async getBooksByAuthorKey(req: Request, res: Response) {
    const books = await BookServer.findBookByAuthorKey(req.body.bookAuthorKey);
    if (!books) return res.error('查询失败！');
    res.success(books);
  }
}

export default new BookController();